<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">

      <el-breadcrumb-item><i class="el-icon-platform-eleme"></i> 角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div>
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入角色名称" v-model="query.roleName">
              <el-button slot="append" icon="el-icon-search" @click="getRoles"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" v-has-permission="'sys:role:sava'" @click="addRoleDialogVisible=true">增加</el-button>
          </el-col>

        </el-row>
        <el-table
            :data="roles"
            stripe
            style="width: 100%">
          <el-table-column
              prop="cname"
              label="角色名称"
              width="100">
          </el-table-column>
          <el-table-column
              prop="dname"
              label="别名"
              width="100">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.row)">修改
              </el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete( scope.row)">删除
              </el-button>
              <el-button
                  size="mini"
                  type="warning"
                  @click="handleRight(scope.row)">权限分配
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="query.curPage"
            :page-sizes="[5, 10, 15, 30]"
            :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-card>

      <el-dialog
          title="角色新增"
          :visible.sync="addRoleDialogVisible"
          width="50%"
          @close="clearFrom">
        <el-form ref="addForm" :rules="rules" :model="role" label-width="50px">
          <el-form-item label="名称" prop="cname">
            <el-input v-model="role.cname"></el-input>
          </el-form-item>
          <el-form-item label="别名" prop="dname">
            <el-input v-model="role.dname"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="role.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </span>
      </el-dialog>


      <el-dialog
          title="修改角色"
          :visible.sync="editRoleDialogVisible"
          width="50%"
          @close="clearEditFrom">
        <!--校验规则  :rules="rules"   prop  表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的 -->
        <el-form ref="editForm" :rules="rules" :model="role" label-width="50px">
          <el-form-item label="名称" prop="cname">
            <el-input v-model="role.cname"></el-input>
          </el-form-item>
          <el-form-item label="别名" prop="dname">
            <el-input v-model="role.dname"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="role.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditRole">确 定</el-button>
        </span>
      </el-dialog>


      <el-dialog
          title="权限分配"
          :visible.sync="rightDialogVisible"
          width="50%" @close="$refs.tree.setCheckedKeys([])">
        <el-tree
            :data="rights"
            show-checkbox
            node-key="id"
            ref="tree"
            default-expand-all
            :default-checked-keys="checkKeys"
            :props="defaultProps">
        </el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="rightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="savRights">确 定</el-button>
         </span>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import {getData, postData, delData, putData} from "../../api/index";

/*await  异步传值  */

export default {
  name: "Roles",
  mounted() {
    this.getRoles()
    this.getRights()
  },

  methods: {

    async savRights(){
      const  _this =this;
      /*tree.getHalfCheckedKeys()获取半角   tree.getCheckedKeys()获取全角*/
      const keys=[...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
      /*map(k=>  组合一个map*/
      const rolePerms =keys.map(k=>{
        return{
          roleid:_this.roleId,
          permid:k
        }
      })
      const res =await postData('sys/perm/saveRight/'+_this.roleId,rolePerms)
      if (res.code === 20000) {
        _this.$message.success(res.msg)
        _this.rightDialogVisible =false;
      }else {
        _this.message.error(res.msg)
      }
    },

    async getRights() {
      const res = await getData('sys/perm/right')
      if (res.code === 20000) {
        this.rights = res.data
      }
    },
    async handleRight(roleInfo) {
      const _this = this;
      _this.roleId =roleInfo.id
      const res = await getData('sys/perm/' + roleInfo.id)
      if (res.code === 20000) {
        _this.checkKeys =res.data;
      }
      this.rightDialogVisible = true;
    },

    async handleDelete(roleInfo) {
      const _this = this;
      this.$confirm('您真的要删除' + roleInfo.cname + '角色吗？ 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await delData('sys/role/' + roleInfo.id);
        if (res.code === 20000) {
          _this.$message.success(res.msg);
          await _this.getRoles();
        } else {
          _this.$message.error(res.msg);
        }
      }).catch(() => {

        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    saveEditRole() {
      const _this = this;
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          const res = await putData('sys/role/' + _this.role.id, _this.role);
          if (res.code === 20000) {
            _this.$refs.editForm.resetFields();
            _this.$message.success(res.msg);
            await _this.getRoles();
            _this.editRoleDialogVisible = false;

          } else {
            _this.$message.error(res.msg);
          }
        } else {
          return false;
        }
      });
    },

    handleEdit(roleInfo) {
      /*深拷贝  创建新对象*/
      this.role = Object.assign(roleInfo);/*   this.role= JSON.parse(JSON.stringify(roleInfo));   */

      this.editRoleDialogVisible = true;
    },

    clearEditFrom() {
      this.role = {}
      this.$refs.editForm.resetFields();
    },

    clearFrom() {
      this.role = {}
      this.$refs.addForm.resetFields();
    },


    async saveRole() {
      const _this = this;
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const res = await postData('sys/role', _this.role);
          if (res.code === 20000) {
            _this.$refs.addForm.resetFields();/*重置*/
            _this.$message.success(res.msg);
            await _this.getRoles();
            _this.addRoleDialogVisible = false;
          } else {
            _this.$message.error(res.msg);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    async getRoles() {
      const _this = this
      const res = await getData('sys/role/list', _this.query)
      if (res.code === 20000) {
        _this.roles = res.data.rows
        _this.total = res.data.total
      }
      console.log(res.data)
    },
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getRoles();
    },
    handleCurrentChange(val) {
      this.query.curPage = val;
      this.getRoles();
    }
  },

  data() {
    return {
      roleId:-1,
      checkKeys:[],
      role: {
        cname: '',
        dname: '',
        description: ''
      },
      total: 0,
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      rightDialogVisible: false,
      query: {
        roleName: '',
        curPage: 1,
        pageSize: 5,
      },
      roles: [],

      rules: {
        cname: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        dname: [
          {required: true, message: '请输入角色别名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
      },

      rights: [],
      defaultProps: {
        children: 'children',
        label: 'cname'
      }
    }
  }
}


</script>

<style scoped>

</style>